// 物理常数
const EPSILON_0 = 8.85e-12; // 真空介电常数 (F/m)
const SCALE_FACTOR = 1e-4; // 单位转换因子

// 全局变量
let animationId = null;
let isAnimating = false;
let animationTime = 0;

// 获取DOM元素
const canvas = document.getElementById('capacitorCanvas');
const ctx = canvas.getContext('2d');

// 获取滑块元素
const chargeSlider = document.getElementById('chargeSlider');
const areaSlider = document.getElementById('areaSlider');
const distanceSlider = document.getElementById('distanceSlider');
const dielectricSlider = document.getElementById('dielectricSlider');

// 获取显示元素
const chargeValue = document.getElementById('chargeValue');
const areaValue = document.getElementById('areaValue');
const distanceValue = document.getElementById('distanceValue');
const dielectricValue = document.getElementById('dielectricValue');

// 获取计算结果显示元素
const capacitanceDisplay = document.getElementById('capacitance');
const electricFieldDisplay = document.getElementById('electricField');
const voltageDisplay = document.getElementById('voltage');
const energyDisplay = document.getElementById('energy');

// 获取控制按钮
const playBtn = document.getElementById('playBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');

// 初始化参数
let params = {
    charge: 50, // μC
    area: 100, // cm²
    distance: 5, // mm
    dielectric: 1.0 // 相对介电常数
};

// 事件监听器
chargeSlider.addEventListener('input', updateCharge);
areaSlider.addEventListener('input', updateArea);
distanceSlider.addEventListener('input', updateDistance);
dielectricSlider.addEventListener('input', updateDielectric);

playBtn.addEventListener('click', startAnimation);
pauseBtn.addEventListener('click', pauseAnimation);
resetBtn.addEventListener('click', resetAnimation);

// 更新参数函数
function updateCharge() {
    params.charge = parseFloat(chargeSlider.value);
    chargeValue.textContent = params.charge;
    updateCalculations();
    drawCapacitor();
}

function updateArea() {
    params.area = parseFloat(areaSlider.value);
    areaValue.textContent = params.area;
    updateCalculations();
    drawCapacitor();
}

function updateDistance() {
    params.distance = parseFloat(distanceSlider.value);
    distanceValue.textContent = params.distance;
    updateCalculations();
    drawCapacitor();
}

function updateDielectric() {
    params.dielectric = parseFloat(dielectricSlider.value);
    dielectricValue.textContent = params.dielectric.toFixed(1);
    updateCalculations();
    drawCapacitor();
}

// 计算物理量
function calculatePhysics() {
    // 单位转换
    const charge_C = params.charge * 1e-6; // C
    const area_m2 = params.area * 1e-4; // m²
    const distance_m = params.distance * 1e-3; // m
    
    // 计算电容
    const capacitance = (EPSILON_0 * params.dielectric * area_m2) / distance_m;
    
    // 计算电场强度
    const electricField = charge_C / (EPSILON_0 * params.dielectric * area_m2);
    
    // 计算电势差
    const voltage = charge_C / capacitance;
    
    // 计算储能
    const energy = 0.5 * capacitance * voltage * voltage;
    
    return {
        capacitance: capacitance,
        electricField: electricField,
        voltage: voltage,
        energy: energy
    };
}

// 更新显示
function updateCalculations() {
    const results = calculatePhysics();
    
    // 更新显示，使用合适的单位
    capacitanceDisplay.textContent = (results.capacitance * 1e9).toFixed(2) + ' nF';
    electricFieldDisplay.textContent = (results.electricField / 1000).toFixed(2) + ' kV/m';
    voltageDisplay.textContent = (results.voltage * 1000).toFixed(2) + ' V';
    energyDisplay.textContent = (results.energy * 1000).toFixed(3) + ' mJ';
    
    // 添加更新动画
    [capacitanceDisplay, electricFieldDisplay, voltageDisplay, energyDisplay].forEach(el => {
        el.classList.add('value-update');
        setTimeout(() => el.classList.remove('value-update'), 300);
    });
}

// 绘制电容器
function drawCapacitor() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    
    // 计算极板尺寸（根据面积缩放）
    const plateWidth = Math.sqrt(params.area) * 2; // 缩放因子
    const plateHeight = 20;
    const plateDistance = params.distance * 5; // 缩放因子
    
    // 绘制上极板（正极）
    ctx.fillStyle = '#ef4444';
    ctx.fillRect(centerX - plateWidth/2, centerY - plateDistance/2 - plateHeight, plateWidth, plateHeight);
    
    // 绘制下极板（负极）
    ctx.fillStyle = '#3b82f6';
    ctx.fillRect(centerX - plateWidth/2, centerY + plateDistance/2, plateWidth, plateHeight);
    
    // 绘制介电质
    if (params.dielectric > 1) {
        ctx.fillStyle = `rgba(34, 197, 94, ${(params.dielectric - 1) / 10})`;
        ctx.fillRect(centerX - plateWidth/2 - 10, centerY - plateDistance/2, plateWidth + 20, plateDistance);
    }
    
    // 绘制电荷粒子
    drawCharges(centerX, centerY, plateWidth, plateDistance);
    
    // 绘制电场线
    drawElectricField(centerX, centerY, plateWidth, plateDistance);
    
    // 绘制标签
    ctx.fillStyle = '#1f2937';
    ctx.font = '14px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(`+Q = ${params.charge} μC`, centerX, centerY - plateDistance/2 - 30);
    ctx.fillText(`-Q = ${params.charge} μC`, centerX, centerY + plateDistance/2 + 40);
}

// 绘制电荷粒子
function drawCharges(centerX, centerY, plateWidth, plateDistance) {
    const chargeCount = Math.min(20, Math.floor(params.charge / 5));
    
    // 正电荷（红色+）
    ctx.fillStyle = '#ef4444';
    ctx.font = '12px Arial';
    for (let i = 0; i < chargeCount; i++) {
        const x = centerX - plateWidth/2 + (i + 0.5) * (plateWidth / chargeCount);
        const y = centerY - plateDistance/2 - 10;
        ctx.fillText('+', x, y);
    }
    
    // 负电荷（蓝色-）
    ctx.fillStyle = '#3b82f6';
    for (let i = 0; i < chargeCount; i++) {
        const x = centerX - plateWidth/2 + (i + 0.5) * (plateWidth / chargeCount);
        const y = centerY + plateDistance/2 + 15;
        ctx.fillText('-', x, y);
    }
}

// 绘制电场线
function drawElectricField(centerX, centerY, plateWidth, plateDistance) {
    const fieldStrength = params.charge / params.area; // 简化表示
    const lineCount = Math.min(15, Math.max(5, Math.floor(fieldStrength)));
    
    ctx.strokeStyle = '#6b7280';
    ctx.lineWidth = 1;
    
    for (let i = 0; i < lineCount; i++) {
        const x = centerX - plateWidth/2 + (i + 0.5) * (plateWidth / lineCount);
        
        // 绘制电场线
        ctx.beginPath();
        ctx.moveTo(x, centerY - plateDistance/2);
        ctx.lineTo(x, centerY + plateDistance/2);
        
        // 添加箭头
        const arrowY = centerY - plateDistance/4;
        ctx.moveTo(x - 3, arrowY - 3);
        ctx.lineTo(x, arrowY);
        ctx.lineTo(x + 3, arrowY - 3);
        
        ctx.stroke();
    }
}

// 动画控制
function startAnimation() {
    if (!isAnimating) {
        isAnimating = true;
        animate();
    }
}

function pauseAnimation() {
    isAnimating = false;
    if (animationId) {
        cancelAnimationFrame(animationId);
    }
}

function resetAnimation() {
    pauseAnimation();
    animationTime = 0;
    drawCapacitor();
}

function animate() {
    if (!isAnimating) return;
    
    animationTime += 0.02;
    
    // 简单的动画效果：电荷闪烁
    const alpha = 0.5 + 0.3 * Math.sin(animationTime * 5);
    drawCapacitor();
    
    // 添加闪烁效果
    ctx.globalAlpha = alpha;
    drawCharges(canvas.width/2, canvas.height/2, Math.sqrt(params.area) * 2, params.distance * 5);
    ctx.globalAlpha = 1;
    
    animationId = requestAnimationFrame(animate);
}

// 初始化
function init() {
    updateCalculations();
    drawCapacitor();
}

// 页面加载完成后初始化
window.addEventListener('load', init);

// 响应式调整
window.addEventListener('resize', () => {
    const container = canvas.parentElement;
    const rect = container.getBoundingClientRect();
    canvas.width = Math.min(400, rect.width - 32);
    canvas.height = 300;
    drawCapacitor();
});